package people;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Package  people
 * Project ChatSystemG2 - INSA 4INFOA1 - 2013/2014
 * 
 * LocalUser represents the client of the chat system
 * It contains the following attributes:  
 *
 * @author Sergio Gonzalez - Marie-Charlotte Bideaud
 */

public class LocalUser extends User {

	private InetAddress broadcast;
	private int udpPort;
	private int tcpPort;

	/** 
	 * Constructor of the class LocalUser
	 * @param username : String
	 * @param type : UserType
	 * @param udpPort : int
	 * @param tcpPort : int
	 * @throws UnknownHostException, SocketException
	 */
	
	public LocalUser(String username, UserType type, int udpPort, int tcpPort) throws UnknownHostException, SocketException{
		super(username, type);
		this.setUdpPort(udpPort);
		this.setTcpPort(tcpPort);
		this.setIPAddr(InetAddress.getLocalHost());
		setBroadcast(findBroadcast());
	}
	
	/** 
	 * Method used to find the broadcast IP using the localhost ip. 
	 * It can be used only with linux.
	 * @return InetAddress
	 * @throws UnknownHostException, SocketException
	 */

	public InetAddress findBroadcast() throws SocketException{
		// Broadcast the message over all the network interfaces
		InetAddress broadcastAddress = null;
		Enumeration<NetworkInterface> interfaces = null;
		interfaces = NetworkInterface.getNetworkInterfaces();
		while (interfaces.hasMoreElements()) {
			NetworkInterface networkInterface = interfaces.nextElement();
			if (networkInterface.isLoopback()) {
				continue; // Don't want to broadcast to the loopback interface
			}
			for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
				broadcastAddress = interfaceAddress.getBroadcast();
				if (broadcastAddress == null) {
					continue;
				} else {
					break;
				}
			}
			if (broadcastAddress != null) {
				break;
			}
		}
		return broadcastAddress;
	}
	
	/** 
	 * Getter of broadcast
	 * @return InetAddress
	 */

	public InetAddress getBroadcast() {
		return broadcast;
	}
	
	/** 
	 * Setter of broadcast
	 * @param broadcast : InetAddress
	 */

	public void setBroadcast(InetAddress broadcast) {
		this.broadcast = broadcast;
	}
	
	/** 
	 * Getter of udpPort
	 * @return int
	 */

	public int getUdpPort() {
		return udpPort;
	}

	/** 
	 * Setter of udpPort
	 * @param udpPort : int
	 */
	
	public void setUdpPort(int udpPort) {
		this.udpPort = udpPort;
	}
	
	/** 
	 * Getter of tcpPort
	 * @return int
	 */

	public int getTcpPort() {
		return tcpPort;
	}
	
	/** 
	 * Setter of tcpPort
	 * @param tcpPort : int
	 */

	public void setTcpPort(int tcpPort) {
		this.tcpPort = tcpPort;
	}
	
}
